/**Created by the LayaAirIDE*/
module view{
	import LuckDarw = view.dlg.LuckDarw;
	import Sign = view.dlg.sign;
	import Tween = laya.utils.Tween;

	export class Farm extends ui.FarmUI{
		//地块对象列表
		private fieldList = {};
		//扩建木牌
		private imgExpand = new Laya.Image();
		public static luckDarw:LuckDarw;
		public static sign:Sign;

		constructor(){
			super();
			this.imgExpand.loadImage("main/expand.png");
			this.imgExpand.anchorX = 0.5;
			this.imgExpand.anchorY = 1;

			this.BindEvent();
			this.btnWarehouse.on(Laya.Event.CLICK, this, this.onClickWarehouse);
			this.btnRank.on(Laya.Event.CLICK, this, this.OnBtnRankClick);
			this.signImg.on(Laya.Event.CLICK,this,this.signInit);
			this.signShowAnimation()
			this.dial_ani.play();
		}

		BindEvent() {
			this.dialbtn.on(Laya.Event.CLICK, this, this.LuckDarwFun);
			this.taskbg.on(Laya.Event.CLICK, this, this.showTask);
			this.taskbg.getChildByName("bubble").on(Laya.Event.CLICK, this, this.showTask);
			this.mailbtn.on(Laya.Event.CLICK, this, this.showMail);
			this.fertilizeBg.getChildByName("cancel").on(Laya.Event.CLICK, this, this.hideFertilize);
		}

		OnBtnRankClick() {
			CtrlManager.GetCtrl(CtrlNames.Rank).ShowRank();
		}
		
		signShowAnimation():void{
			this.sing_ani.play();
		}
		Init(baseData:any) : void {
			this.labscore.text = baseData.score.toString();
		}

		//设置地块数据
		SetField() : void {
			let fieldNum = FieldModel.GetFieldNum();
			let fieldList = FieldModel.GetFieldList();
			let stageList = FieldModel.GetStageList();
			//清除之前的地块
			for (let i in this.fieldList) {
				let oldField = this.fieldList[i];
				oldField.RemoveField();
				delete this.fieldList[i];
				Laya.Pool.recover("field", oldField);
			}
			
			//添加地块
			if (fieldNum > 0 ) {
				for (let j = 0; j < fieldNum; j++) {
					let index = j+1;
					let newField = Laya.Pool.getItemByClass("field", Field);
					let arrayIndex = ComFun.GetArrayValueIndex(fieldList,"index",index);
					if (null == arrayIndex) {
						newField.Init({index : index});
					} else {
						let fieldData = fieldList[arrayIndex];
						fieldData.stage = stageList[index];
						newField.Init(fieldData);
					}
					this.fieldList[index] = newField;
				}
			}

			//设置木牌
			this.SetImgExpand(fieldNum+1);
		}

		//设置木牌
		SetImgExpand(index:number) : void {
			this.imgExpand.offAll(Laya.Event.CLICK);
			this.imgExpand.removeSelf();
			if (index <= Cfg.CommonCfg["fieldTotal"]) {
				let fieldBgName = "fieldbg" + index.toString();
				let fieldBg = this.boxField.getChildByName(fieldBgName) as Laya.Image;
				let expandX = Math.floor(fieldBg.width/2);
				let expandY = Math.floor(fieldBg.height*4/5);
				this.imgExpand.pos(expandX, expandY);
				this.imgExpand.on(Laya.Event.CLICK, this, this.OnExpandClick);
				fieldBg.addChild(this.imgExpand);
			}
		}

		OnExpandClick() : void {
			ComFun.BaseCall("expand");
		}

		LuckDarwFun():void {
			CtrlManager.GetCtrl(CtrlNames.Darw).getDarwData();
			
		}
		LuckDarwRsq(physical:number,textTime:number):void {
			if(!view.Farm.luckDarw){
				// let data = darwModel.getDarwNum();
				// view.Farm.luckDarw = new LuckDarw(data["physical"],data["textTime"]);
				view.Farm.luckDarw = new LuckDarw(physical,textTime);
			}
			Laya.timer.loop(1000,this,this.showSurplusTime);
			view.Farm.luckDarw.popup();
		}

		showSurplusTime():void{
			view.Farm.luckDarw.showSurplusTime();
		}
		//显示任务
		showTask():void{
			CtrlManager.GetCtrl(CtrlNames.Task).showTask();
		}

		//种植农作物到地块
		Plant(index:number, cropId:number) : void {
			let curField = this.fieldList[index];
			curField.Plant(cropId);
			PlaySound.getPlaySound().playPlant();
		}

		onClickWarehouse()
		{
			CtrlManager.GetCtrl(CtrlNames.Warehouse).SetSeedData();
			CtrlManager.GetCtrl(CtrlNames.Warehouse).ShowDlg();
			// CtrlManager.GetCtrl(CtrlNames.Warehouse).SendSeedReq();
			// CtrlManager.GetCtrl(CtrlNames.Warehouse).ShowDlg();
		}
		
		//改变农作物状态
		ChangeState(index:number, stage:number) : void {
			let curField = this.fieldList[index];
			curField.ChangeState(stage);
		}

		//收获
		Harvest(index:number) : void {
			let curField = this.fieldList[index];
			curField.Harvest();
			PlaySound.getPlaySound().playHarvest();
		}

		//偷取成功,服务器回调
		stealSuccess(index : number, stealScore : number){
			let curField = this.fieldList[index];
			curField.stealSuccess(stealScore);
			PlaySound.getPlaySound().playHarvest();
		}

		//设置积分
		SetScore() : void {
			this.labscore.text = PlayerModel.GetScore().toString();
		}

		//设置地块数量
		SetFieldNum(fieldNum:number) : void {
			this.SetImgExpand(fieldNum+1);
			let newField = Laya.Pool.getItemByClass("field", Field);
			newField.Init({index : fieldNum});
			this.fieldList[fieldNum] = newField;
		}

		//设置天气
		SetWeather() {
			this.imgWeather.graphics.clear();
			let imgUrl = "main/" + Cfg.WeatherCfg[WeatherModel.GetWeatherId()].skin + ".png";
			this.imgWeather.loadImage(imgUrl);
		}

		//农作物获得灾害
		AddDisaster(fieldIndexArray:any) {
			fieldIndexArray.forEach(index => {
				let curField = this.fieldList[index];
				curField.AddDisaster();
			});
		}

		//清除所有农作物灾害
		ClearAllDisaster() {
			let fieldList = FieldModel.GetFieldList();
			fieldList.forEach(fieldData => {
				let curField = this.fieldList[fieldData.index];
				curField.ClearDisaster();
			});
		}

		//清除指定农作物的灾害
		OnClearDisaster(index:number) {
			let curField = this.fieldList[index];
			curField.ClearDisaster();
		}

		//显示作物描叙
		showCropTips(point : Laya.Point, index : number):void{
			let field =ComFun.GetArrayValue(FieldModel.GetFieldList(),"index",index);
			let crop = Cfg.ItemCfg[field["cropId"]];
			this.cropTips.x = point.x / this.boxGround.scaleX;
			this.cropTips.y = point.y / this.boxGround.scaleY;
			this.cropTips.getChildByName("desName")["text"] =crop["name"];
			let timing = crop["time"] + field["plantTime"] - Game.serverTime;
			let effect = 0;
			let mreward = -field["stealScore"];
			field["disasterList"].forEach(disaster => {
				effect += Cfg.DisasterCfg[disaster]["effect"]
			});
			field["propList"].forEach(prop => {
				if(prop.itemId != 0){
					let propCfg = Cfg.ItemCfg[prop.itemId];
					if(Cfg.ItemCfg["prop_effect_time"]["value"] == propCfg["effect_type"]){
						if(Cfg.ItemCfg["prop_supply_fixed"]["value"] == propCfg["effect_supply"]){
							timing -= propCfg["effect"][0] * prop.number;
						}
					}else if(Cfg.ItemCfg["prop_effect_yield"]["value"] == propCfg["effect_type"]){
						if(Cfg.ItemCfg["prop_supply_permille"]["value"] == propCfg["effect_supply"]){
							effect += propCfg["effect"][0]  * prop.number;
						}else if(Cfg.ItemCfg["prop_supply_fixed"]["value"] == propCfg["effect_supply"]){
							mreward += propCfg["effect"][0]  * prop.number;
						}
					}
				}
			});
			if(timing > 0){
				this.cropTips.getChildByName("desTime")["text"] = ComFun.formatTiming(timing*1000,"d天h小时m分s秒后成熟",false);
			}else{
				this.cropTips.getChildByName("desTime")["text"] = "已成熟";
			}
			mreward += Math.floor((1 + effect / 1000) * crop["score"]);
			if(field["stealScore"]>0){
				this.cropTips.getChildByName("desSteal")["text"] = "被偷: "+field["stealScore"]+"积分";
			}else{
				this.cropTips.getChildByName("desSteal")["text"] = "";
			}
			if(effect == 0){
				this.cropTips.getChildByName("desScore")["color"] = "#422304";
				this.cropTips.getChildByName("desScore")["text"] = mreward +"积分";
			}else if(effect > 0){
				this.cropTips.getChildByName("desScore")["color"] = "#178b17";
				this.cropTips.getChildByName("desScore")["text"] = mreward +"积分(增产" + (effect / 10) +"%)";
			}else{
				this.cropTips.getChildByName("desScore")["color"] = "red";
				if(mreward < crop["mreward"]){
					this.cropTips.getChildByName("desScore")["text"] = crop["mreward"] + "积分(减产" + Math.floor((1 - crop["mreward"]/crop["score"]) * 100) +"%)";
				} else{
					this.cropTips.getChildByName("desScore")["text"] = mreward + "积分(减产" + (-effect / 10) +"%)";
				}
			}
			this.cropTips.visible = true;
			Laya.timer.once(100,this,this.cropTipsTimer);
		}

		cropTipsTimer() : void{
			this.once(Laya.Event.MOUSE_DOWN,this,this.hideCropTips);
		}
		//隐藏作物描叙
		hideCropTips() : void{
			this.cropTips.visible = false;
		}

		//弹出邮件面板
		showMail()
		{
			CtrlManager.GetCtrl(CtrlNames.Mail).ShowDlg();
		}
		//获取签到表
		signInit():void{
			if(!view.Farm.sign){
				view.Farm.sign = new Sign();
			}
			CtrlManager.GetCtrl(CtrlNames.Sign).sendSignTable();
			view.Farm.sign.popup();
		}

		//显示遮罩云
		showMaskCloud(){
			Tween.to(this.maskCloud,{x : this.maskCloud.width},150);
			Laya.timer.once(5000, this, this.hideMaskCloudError);
		}

		//隐藏遮罩云的定时器,服务器没有返回数据时
		hideMaskCloudError(){
			console.log("获取好友数据失败");
			this.hideMaskCloud();
		}

		//隐藏遮罩云的定时器,服务器有返回数据时
		hideMaskCloudTimer(){
			Laya.timer.clear(this, this.hideMaskCloudError);
			Laya.timer.once(600, this, this.hideMaskCloud);
		}

		//隐藏遮罩云
		hideMaskCloud(){
			Tween.to(this.maskCloud,{x : 0},500);
		}

		//进入好友农场
		EenterFriendFarm() {
			this.hideMaskCloudTimer();
			this.imgScore.visible = false;
			this.imgFriendScore.visible = true;
			this.labFriendScore.text = PlayerModel.GetScore().toString();
			this.labFriendName.visible = true;
			this.labFriendName.text = PlayerModel.GetNickName();
			this.btnWarehouse.visible = false;
			this.btnRank.visible = false;
			this.btnOption.visible = false;
			this.signImg.visible = false;
			this.dialbtn.offAll(Laya.Event.CLICK);
			this.dialbtn.getChildByName("bubble")["visible"] = false;
			this.taskbg.offAll(Laya.Event.CLICK);
			this.taskbg.getChildByName("bubble")["visible"] = false;
			this.mailbtn.offAll(Laya.Event.CLICK);
			this.mailbtn.getChildByName("bubble")["visible"] = false;
			this.imgDogBowl.offAll(Laya.Event.CLICK);
			this.imgDogBowlRemind.offAll(Laya.Event.CLICK);

			this.imgFriendHead.graphics.clear();
			this.imgFriendHead.visible = true;
			if (PlayerModel.GetAvatarUrl().length > 0) {
				this.imgFriendHead.loadImage(PlayerModel.GetAvatarUrl(), 0, 0, 100, 100);
			}
			this.btnHome.visible = true;
			this.btnHome.on(Laya.Event.CLICK, this, this.OnBtnHomeClick);
		}

		OnBtnHomeClick() {
			this.showMaskCloud();
			CtrlManager.GetCtrl(CtrlNames.Friend).LevelFriendFarm();
		}

		//离开好友农场
		LevelFriendFarm() {
			this.hideMaskCloudTimer();
			this.imgScore.visible = true;
			this.btnWarehouse.visible = true;
			this.btnRank.visible = true;
			this.btnOption.visible = true;
			this.signImg.visible = true;
			this.BindEvent();

			this.imgFriendScore.visible = false;
			this.labFriendName.visible = false;
			this.imgFriendHead.visible = false;
			this.btnHome.offAll(Laya.Event.CLICK);
			this.btnHome.visible = false;
		}

		//显示施肥面板
		showFertilize(propId){
			FieldModel.GetFieldList().forEach(element => {
				this.fieldList[element["index"]].showFertilize(propId,FieldModel.GetStageList()[element["index"]]);
			});
			this.fertilizeBg.getChildByName("prop")["skin"] = "item/" + Cfg.ItemCfg[propId]["skin"] + ".png";
			this.fertilizeBg.getChildByName("des")["text"] = Cfg.ItemCfg[propId]["depict"]
			this.fertilizeBg.visible = true;
		}

		//隐藏施肥面板
		hideFertilize(){
			FieldModel.GetFieldList().forEach(element => {
				this.fieldList[element["index"]].hideFertilize();
			});
			this.fertilizeBg.visible = false;
			CtrlManager.GetCtrl(CtrlNames.Warehouse).ShowDlg();
		}

		//进行施肥操作
		onHaveFertilize(propId, count, index){
			console.log("进行一次施肥操作");
			this.fieldList[index].onHaveFertilize(propId,count);
		}

		//设置护盾
		SetShield() {
			let shieldStatus = ShieldModel.GetStatus();
			if (shieldStatus == Cfg.ShieldStatus.Close) {
				this.imgDogBowlRemind.visible = true;
				this.imgDogBowl.loadImage("shield/dogbowl.png");
				this.aniDogSleep.stop();
				this.aniDogWalk.stop();
				this.aniDogSleep.visible = false;
				this.aniDogWalk.visible = false;
				this.imgDogBowlRemind.on(Laya.Event.CLICK, this, this.OnDogBowlClick);
				this.imgDogBowl.on(Laya.Event.CLICK, this, this.OnDogBowlClick);
			} else {
				this.imgDogBowl.offAll(Laya.Event.CLICK);
				this.imgDogBowlRemind.offAll(Laya.Event.CLICK);
				this.imgDogBowlRemind.visible = false;
				if (shieldStatus == Cfg.ShieldStatus.Sleep) {
					this.imgDogBowl.loadImage("shield/dogbowl.png");
					if (!this.aniDogSleep.isPlaying) {
						this.aniDogSleep.play();
					}
					this.aniDogWalk.stop();
					this.aniDogSleep.visible = true;
					this.aniDogWalk.visible = false;
				} else {
					this.imgDogBowl.loadImage("shield/dogbowl2.png");
					this.aniDogSleep.stop();
					if (!this.aniDogWalk.isPlaying) {
						this.aniDogWalk.play();
					}
					this.aniDogSleep.visible = false;
					this.aniDogWalk.visible = true;
				}
			}
		}

		OnDogBowlClick() {
			CtrlManager.GetCtrl(CtrlNames.Shield).ShowInvite();
		}

		//提示
		OnPrompt(id:number) {
			if (Cfg.PromptCfg[id]) {
				let strContent = Cfg.PromptCfg[id].content;
				let objPrompt = Laya.Pool.getItemByClass("prompt", Prompt);
				objPrompt.Show(strContent);
			}
		}

		//提示结束
		PromptEnd(objPrompt:Prompt) {
			if (objPrompt) {
				objPrompt.removeSelf();
				Laya.Pool.recover("prompt", objPrompt);
			}
		}

		ClearSelected() {
			let curField = this.fieldList[FieldModel.GetSelected()];
			if (curField) {
				curField.HideFrame();
			}
			FieldModel.ClearSelected();
		}
	}
}